/*
 * author: Andriamananony, Meß, Falk
 */

package auftrag;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import util.Interval;

public class Ressource {
	private String strRessourceName;
	private ArrayList<Interval> mIntervals = new ArrayList<Interval>();
	private HashMap<Integer, Interval> mLastIntervalOfLength = new HashMap<Integer, Interval>();

	public Ressource(String strRessourceName) {
		this.strRessourceName = strRessourceName;
	}

	@Override
	public String toString() {
		return this.strRessourceName;
	}
	
	public void clear(){
		mIntervals.clear();
		mLastIntervalOfLength.clear();
	}
	
	public int getMaxTime(){
		int i = mIntervals.size();
		if(i > 0)
			return mIntervals.get(mIntervals.size()-1).getEnd();
		return 0;
	}
	
	public boolean addInterval(Interval pI){
		mIntervals.add(pI);
		if(pI.getEnd() - pI.getDuration() < getMaxTime())
			Collections.sort(mIntervals);
		mLastIntervalOfLength.put(pI.getDuration(), pI);
		return true;
	}
	
	public Interval getFirstUnoccupiedInterval(int start, int d){
		Interval last = null;
		int nIndexOfLast = 0;
		/*for(int i = d; i > 0; i--){
			if(mLastIntervalOfLength.containsKey(d)){	
				last = mLastIntervalOfLength.get(d);
				nIndexOfLast = mIntervals.indexOf(last);
				start = Math.max(start, last.getEnd());
				break;
			}
		}*/
		
		Interval tmpCompare = new Interval(start,start+d);
		for(Interval i : mIntervals.subList(nIndexOfLast, mIntervals.size())){
			if(i.overlapsWith(tmpCompare)){
				tmpCompare.moveTo(i.getEnd());
			} else if(i.compareTo(tmpCompare) == 1)
				break;
		}
		return tmpCompare;
	}
	
	public double getAuslastung(){
		if(getMaxTime() <= 0)
			return 0;
		double time = 0;
		Collections.sort(mIntervals);
		for(Interval i : mIntervals)
			time += i.getDuration();
		return time / getMaxTime();
	}
}
